<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PK 答题匹配</title>
    <link rel="icon" type="image/ico" href="pc/ico.png">
    <!-- 引入Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-pEMgO+ddVg8/8rY9+/1Z6qDcD5DYmgLaqllfv0TuaeFLFEHzJ9LqpgaFTCOkWdfhRHxh45Q8J+ASb9Qr1XUu6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        /* 通用重置和基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 2rem 1.5rem;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            text-align: center;
            width: 100%;
            max-width: 600px;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        #status, #opponent-info {
            margin: 15px 0;
            font-size: 1.2rem;
            text-align: center;
            max-width: 600px;
        }

        #status {
            color: #555;
        }

        #opponent-info {
            color: #28a745;
            font-weight: bold;
        }

        button {
            padding: 12px 24px;
            font-size: 1rem;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease;
            margin: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        button:hover {
            background-color: #0056b3;
            transform: translateY(-2px);
        }

        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            box-shadow: none;
        }

        #questions {
            display: none;
            margin-top: 30px;
            padding: 2rem;
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 700px;
            transition: all 0.5s ease-in-out;
        }

        #questions h2 {
            margin-bottom: 20px;
            font-size: 2rem;
            color: #333;
            text-align: left;
        }

        .question {
            margin-bottom: 25px;
            font-size: 1.2rem;
            color: #333;
            text-align: left;
            display: none; /* 隐藏所有题目 */
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
        }

        .question.active {
            display: block; /* 仅当前题目显示 */
            opacity: 1;
        }

        .question p {
            margin-bottom: 10px;
            font-weight: bold;
        }

        .options {
            display: flex;
            flex-direction: column;
        }

        .option {
            background-color: #f9f9f9;
            border: 2px solid #ddd;
            border-radius: 8px;
            padding: 10px 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: background-color 0.3s, border-color 0.3s;
            display: flex;
            align-items: center;
        }

        .option:hover {
            background-color: #e6f7ff;
            border-color: #007BFF;
        }

        .option input {
            margin-right: 10px;
            transform: scale(1.2);
            cursor: pointer;
        }

        /* 刷新按钮样式优化 */
        .cta {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 12px 24px;
            text-decoration: none;
            font-size: 1.2rem;
            color: white;
            background: #6f42c1;
            transition: background-color 0.3s ease, transform 0.2s ease;
            border-radius: 30px;
            cursor: pointer;
            margin-top: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .cta:hover {
            background-color: #5a32a3;
            transform: translateY(-2px);
        }

        .cta .span {
            margin-right: 10px;
            font-weight: bold;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header h1 {
                font-size: 2rem;
            }

            .header p {
                font-size: 1rem;
            }

            #questions h2 {
                font-size: 1.5rem;
            }

            button, .cta {
                width: 100%;
                max-width: 300px;
            }

            .question {
                font-size: 1rem;
            }

            .question p {
                font-size: 1rem;
            }

            .option {
                font-size: 0.9rem;
            }

            .cta {
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
<header class="header">
    <h1>PK 答题匹配</h1>
    <p>实时匹配，展开答题对决</p>
</header>

<div id="status">正在连接到匹配服务器...</div>
<div id="opponent-info"></div>
<button id="startMatch" disabled><i class="fas fa-user-friends"></i> 开始匹配</button>

<div id="questions">
    <h2>答题区</h2>
    <div id="progress-container" style="width: 100%; max-width: 700px; margin-top: 10px; height: 20px; background-color: #e0e0e0; border-radius: 10px;">
        <div id="progress-bar" style="height: 100%; width: 0%; background-color: #28a745; border-radius: 10px; transition: width 0.3s;"></div>
    </div>
    <div id="question-container"></div>
</div>

<!-- 新增刷新页面的按钮 -->
<button class="cta" id="refreshPageButton" style="display: none;">
    <span class="span">刷新页面</span>
    <span class="second">
        <i class="fas fa-redo-alt"></i>
    </span>
</button>

<script>
    let socket;
    let opponentId = null;
    let questions = [];
    let userScore = 0;
    let opponentScore = null; // 初始值为 null，表示尚未接收到对方分数
    let userId = null; // 动态获取用户ID
    const subjectId = 1; // 假设科目 ID，实际由前端选择
    const statusDiv = document.getElementById("status");
    const opponentInfoDiv = document.getElementById("opponent-info");
    const startMatchButton = document.getElementById("startMatch");
    const questionsDiv = document.getElementById("questions"); // 答题区域
    const questionContainer = document.getElementById("question-container"); // 问题容器
    const refreshPageButton = document.getElementById("refreshPageButton"); // 刷新按钮
    let isResultDisplayed = false; // 防止重复显示结果
    let currentQuestionIndex = 0; // 当前题目的索引，用于逐题展示
    let selectedAnswers = {}; // 存储用户的选择

    // 获取用户信息
    async function fetchUserInfo() {
        try {
            const response = await fetch("/api/v1/users/getUserInfo", {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                },
            });
            const result = await response.json();
            if (result.code === 200) {
                userId = result.data.id; // 动态获取用户ID
                connectWebSocket(); // 确保这里调用了 connectWebSocket
            } else {
                console.error("获取用户信息失败:", result.message);
                statusDiv.innerText = "获取用户信息失败，请重新登录！";
            }
        } catch (error) {
            console.error("获取用户信息时发生错误:", error);
            statusDiv.innerText = "获取用户信息时发生错误，请检查网络连接！";
        }
    }

    // 初始化 WebSocket 连接
    function connectWebSocket() {
        socket = new WebSocket("ws://101.34.242.206:9999/ws/game");
        socket.onopen = () => {
            console.log("WebSocket 连接已建立");
            statusDiv.innerText = "连接成功";
            startMatchButton.disabled = false;
        };

        socket.onmessage = async (event) => {
            try {
                const message = JSON.parse(event.data);

                if (message.status === "matched") {
                    opponentId = message.opponentId;
                    opponentInfoDiv.innerText = `匹配成功！对手ID: ${opponentId}`;
                    statusDiv.innerText = "进入答题模式...";
                    await fetchQuestions();
                } else if (message.status === "waiting") {
                    statusDiv.innerText = "匹配中，请稍候...";
                } else if (message.action === "result") {
                    handleMatchResult(message);
                } else {
                    console.warn("未知的 WebSocket 消息:", message);
                }
            } catch (error) {
                console.error("WebSocket 消息解析失败:", error);
                statusDiv.innerText = "服务器出现问题，请稍后再试。";
            }
        };

        socket.onclose = () => {
            statusDiv.innerText = "连接断开，尝试重新连接...";
            setTimeout(connectWebSocket, 3000);
        };

        socket.onerror = (error) => {
            console.error("WebSocket 错误:", error);
            statusDiv.innerText = "服务器出现错误，请稍后重试";
        };
    }

    // 获取题目
    async function fetchQuestions() {
        statusDiv.innerText = "正在加载题目...";
        try {
            const response = await fetch(`/api/v1/questions/fetch?limit=10&subjectId=${subjectId}`, {
                method: "GET",
                headers: { "Content-Type": "application/json" },
            });
            const result = await response.json();
            if (result.code === 200) {
                questions = result.data;
                currentQuestionIndex = 0;
                selectedAnswers = {};
                renderQuestion(questions[currentQuestionIndex]);
                statusDiv.innerText = "题目已加载，请开始答题";
                questionsDiv.style.display = "block"; // 显示答题区域
            } else {
                console.error("加载题目失败", result.message);
                statusDiv.innerText = "加载题目失败，请稍后重试。";
            }
        } catch (error) {
            console.error("加载题目时发生错误", error);
            statusDiv.innerText = "加载题目时发生错误，请检查网络连接！";
        }
    }

    // 渲染单个题目
    function renderQuestion(question) {
        questionContainer.innerHTML = ""; // 清空旧题目

        const questionDiv = document.createElement("div");
        questionDiv.className = "question active"; // 仅当前题目显示

        questionDiv.innerHTML = `
            <p>${currentQuestionIndex + 1}. ${question.questionText}</p>
            <div class="options">
                ${question.options.map(opt => `
                    <label class="option">
                        <input type="radio" name="question-${question.questionId}" value="${opt.optionLabel}" />
                        <span>${opt.optionLabel}. ${opt.optionText}</span>
                    </label>
                `).join("")}
            </div>
        `;
        questionContainer.appendChild(questionDiv);

        // Add event listeners to options
        const optionInputs = questionDiv.querySelectorAll("input[type='radio']");
        optionInputs.forEach(input => {
            input.addEventListener("change", () => {
                // Store the selected answer
                selectedAnswers[question.questionId] = input.value;

                // Proceed to next question after a delay
                setTimeout(() => {
                    currentQuestionIndex++;
                    if (currentQuestionIndex < questions.length) {
                        renderQuestion(questions[currentQuestionIndex]);
                    } else {
                        // All questions answered, automatically submit answers
                        submitAnswers();
                    }
                }, 300); // 300ms delay
            });
        });

        // 更新进度条
        const progressBar = document.getElementById("progress-bar");
        if (progressBar) {
            const progressPercentage = ((currentQuestionIndex + 1) / questions.length) * 100;
            progressBar.style.width = `${progressPercentage}%`;
        }
    }

    // 提交答案
    async function submitAnswers() {
        // 组织答案数据
        const answers = questions.map(q => ({
            questionId: q.questionId,
            userAnswer: selectedAnswers[q.questionId],
            subjectId: q.subjectId,
        }));

        try {
            const response = await fetch("/api/v1/questions/submit", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(answers),
            });

            const result = await response.json();
            if (result.code === 200) {
                calculateScore(result.data);
            } else {
                console.error("提交答案失败", result.message);
                statusDiv.innerText = "答案提交失败，请稍后重试。";
            }
        } catch (error) {
            console.error("提交答案时发生错误", error);
            statusDiv.innerText = "答案提交时发生错误，请检查网络连接。";
        }
    }

    // 分数计算逻辑
    function calculateScore(results) {
        userScore = results.reduce((total, r) => (r.correct ? total + 10 : total), 0); // 每答对一题得10分
        socket.send(
            JSON.stringify({
                action: "finish",
                userId,
                opponentId,
                userScore,
                subjectId,
            })
        );

        statusDiv.innerText = `答题完成，您的得分为: ${userScore} 分，等待比赛结果...`;
    }

    // 处理比赛结果
    function handleMatchResult(message) {
        if (isResultDisplayed) return;
        isResultDisplayed = true;

        opponentScore = message.opponentScore;
        userScore = message.userScore;

        renderMatchResult(userScore, opponentScore);
    }

    // 渲染比赛结果
    function renderMatchResult(userScore, opponentScore) {
        opponentInfoDiv.innerText = `比赛结束！您的得分: ${userScore}，对手得分: ${opponentScore}`;

        if (userScore > opponentScore) {
            statusDiv.innerText = "您赢了！🎉";
            statusDiv.style.color = "#28a745";
        } else if (userScore < opponentScore) {
            statusDiv.innerText = "您输了！😢";
            statusDiv.style.color = "#dc3545";
        } else {
            statusDiv.innerText = "平局！🤝";
            statusDiv.style.color = "#ffc107";
        }

        // 显示刷新按钮
        refreshPageButton.style.display = "flex"; // 无论输赢，都显示刷新按钮
    }

    // 刷新页面按钮点击事件
    refreshPageButton.addEventListener("click", () => {
        resetMatch(); // 清理匹配状态
        window.location.reload(); // 刷新页面
    });

    // 页面加载时获取用户信息并初始化
    document.addEventListener("DOMContentLoaded", async () => {
        console.log("DOMContentLoaded triggered");
        await fetchUserInfo();
    });

    // 启动匹配
    startMatchButton.addEventListener("click", () => {
        startMatchButton.disabled = true;
        statusDiv.innerText = "匹配中，请稍候...";
        socket.send(JSON.stringify({ action: "match" }));
    });

    // 清理匹配状态，准备重新匹配
    function resetMatch() {
        currentQuestionIndex = 0;
        userScore = 0;
        opponentScore = null;
        questions = [];
        isResultDisplayed = false;
        opponentId = null;
        statusDiv.innerText = "正在连接到匹配服务器...";
        statusDiv.style.color = "#555"; // 重置颜色
        opponentInfoDiv.innerText = "";
        startMatchButton.disabled = true;
        questionsDiv.style.display = "none";
        refreshPageButton.style.display = "none";
    }
</script>

</body>
</html>
